package interview;

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache {
}

import java.util.LinkedHashMap;
        import java.util.Map;

public class LRUCache<K, V> extends LinkedHashMap<K, V> {
    private final int cacheSize;

    public LRUCache(int cacheSize) {
        // accessOrder 为 true 表示按照访问顺序排序
        super(cacheSize, 0.75f, true);
        this.cacheSize = cacheSize;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > cacheSize;
    }

    public static void main(String[] args) {
        LRUCache<Integer, String> lruCache = new LRUCache<>(3);

        lruCache.put(1, "one");
        lruCache.put(2, "two");
        lruCache.put(3, "three");
        System.out.println(lruCache); // 输出: {1=one, 2=two, 3=three}

        lruCache.get(1); // 访问 key 1
        lruCache.put(4, "four"); // 超出缓存大小，移除最久未使用的 key 2
        System.out.println(lruCache); // 输出: {1=one, 3=three, 4=four}

        lruCache.put(5, "five"); // 超出缓存大小，移除最久未使用的 key 1
        System.out.println(lruCache); // 输出: {3=three, 4=four, 5=five}
    }
}
